import { Table, Icon, Row, Col, Button, Spin, Modal } from 'antd';

const confirm = Modal.confirm;
import { WeaTools, WeaInput, WeaSelect, WeaBrowser, WeaDatePicker, WeaCheckbox } from 'ecCom';
import './style/index.css';
import equal from 'deep-equal';
import { WeaLocaleProvider } from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;

class ContractPayTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      columns: props.columns || [],
      childColumns: props.childColumns || [],
      datas: [],
      showGroup: props.showGroup ? props.showGroup : false,
      rowKeys: [],
      canEdit: props.canEdit || false,
    };
  }
  componentDidMount() {
    const { datas = [], columns = [] } = this.props;
    columns.length > 0 && this.setState(datas.length > 0 ? { datas: this.addKeytoDatas(datas), columns } : { columns });
  }
  componentWillReceiveProps(nextProps, nextState) {
    if (!equal(this.props.childColumns, nextProps.childColumns)) {
      this.setState({ childColumns: nextProps.childColumns });
    }
    // if(!equal(this.props.columns,nextProps.columns)){
    this.setState({ columns: nextProps.columns });
    // }
	    if (!equal(this.props.datas, nextProps.datas)) {
      this.setState({ datas: this.addKeytoDatas(nextProps.datas) });
    }
  }
  // shouldComponentUpdate(nextProps, nextState) {
  // 	console.log("!equal(this.state.datas,nextState.datas)",!equal(this.state.datas,nextState.datas),this.state.datas,nextState.datas)
  // 	return !equal(this.props.datas, nextProps.datas) ||
  // 		!equal(this.props.columns,nextProps.columns)||
  // 		!equal(this.props.childColumns,nextProps.childColumns)||
  // 		// !equal(this.state,nextState)||
  // 		// !equal(this.state.datas,nextState.datas)||
  // 		!equal(this.props.type,nextProps.type)
  // }
  addKeytoDatas(datas) {
    const rowKeys = [];
    const _datas = datas.map((data, i) => {
      const _data = { ...data };
      _data.key = i;
      rowKeys.push(i);
      return _data;
    });
    this.setState({ rowKeys });
    return _datas;
  }
  render() {
    const { datas, showGroup, columns, rowKeys } = this.state;
    const { title } = this.props;
    return (
      <div className="wea-crm-table-edit" >
        <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@fsdl3s`} className="wea-title">
          <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@vzj1iw`} span="20">
            <div>{title}</div>
          </Col>
          <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@rqg83p`} span="4" style={{ textAlign: 'right', paddingRight: 10 }}>
            <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@31fn4p`} type={showGroup ? 'up' : 'down'} onClick={() => this.setState({ showGroup: !showGroup })} />
          </Col>
        </Row>
        <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@c9gvwv`} className="wea-content" style={{ display: showGroup ? 'block' : 'none' }}>
          <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@8ni1j6`} span={24}>
            <Table
              ecId={`${this && this.props && this.props.ecId || ''}_Table@bcqloc`}
              columns={this.getColumns(columns, 'p')}
              dataSource={datas}
              pagination={false}
              // defaultExpandAllRows={true}
              expandedRowRender={record => this.getExpendRowRender(record)}
              onExpandedRowsChange={(expanded) => { this.expendRowsChange(expanded); }}
              expandedRowKeys={rowKeys}
            />
          </Col>
        </Row>

      </div>
    );
  }
  getColumns(columns, level) {
    let _columns = [].concat(columns);
    _columns = _columns.map((col) => {
      const _col = { ...col };
      _col.render = (text, record, index) => this.getColRender(_col, text, record, index, level);
      return _col;
    });
    return _columns;
  }
  getColRender(_col, text, record, index, level) {
    const { com } = _col;
    const _com = [];
    const { canEdit } = this.state;
    com.map((c) => {
      if (typeof c.props === 'object' && level == 'p') {
        if (canEdit) {
          _com.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@nka5fz@save`} type="primary" title={getLabel(86, '保存')} size="small" style={{ padding: '1px 3px' }} onClick={() => this.saveRowList(record, index)}><Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@c94f0b@save`} type="save" /></Button>);
        }
      } else if (typeof c.props === 'object') {
        if (canEdit) {
          _com.push(<span>
            {/* <Button type="primary" title={getLabel(86,"保存")} size="small" onClick={()=>this.saveDetailList(record, index,"save")}>{getLabel(86,"保存")}</Button> &nbsp;&nbsp;
						<Button type="primary" title={getLabel(91,"删除")} size="small" onClick={()=>this.saveDetailList(record, index,"delet")}>{getLabel(91,"删除")}</Button> */}

            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@2zy9nf@save`} type="primary" title={getLabel(86, '保存')} size="small" onClick={() => this.saveDetailList(record, index, 'save')}><Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@eobh5t@save`} type="save" /></Button>&nbsp;&nbsp;
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@mkt5rn@delete`} type="primary" title={getLabel(91, '删除')} size="small" onClick={() => this.saveDetailList(record, index, 'delet')}><Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@pzhqc1@minus`} type="minus" /></Button>
          </span>);
        }
      } else {
        const { domkey, viewAttr = 2, conditionType = 'INPUT', options = [], browserConditionParam = {}, width, value, type = 'text', otherParams = {} } = c;
        const _type = conditionType.toUpperCase();
        _com.push(
          <span>
            {_type === 'INPUT' &&
            <WeaInput
              ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@inve4q@${domkey[0]}`}
              value={record[domkey[0]]}
              style={{ width, display: 'inline-block' }}
              onChange={value => this.onEdit(record, index, domkey[0], value)}
              viewAttr={viewAttr}
              {...otherParams}
            />
            }
            {_type === 'SELECT' &&
            <WeaSelect
              ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@4yfhrh@${domkey[0]}`}
              options={options}
              value={record[domkey[0]]}
              style={{ width, display: 'inline-block' }}
              onChange={value => this.onEdit(record, index, domkey[0], value)}
              viewAttr={viewAttr}
              {...otherParams}
            />
            }
            { _type === 'DATEPICKER' &&
            <WeaDatePicker
              ecId={`${this && this.props && this.props.ecId || ''}_WeaDatePicker@brkr0r@${domkey[0]}`}
              value={record[domkey[0]]}
              style={{ width, display: 'inline-block' }}
              formatPattern={2}
              viewAttr={viewAttr}
              onChange={value => this.onEdit(record, index, domkey[0], value)}
            />
            }
            { _type === 'CHECKBOX' &&
            <WeaCheckbox
              ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@gk4106@${domkey[0]}`}
              value={record[domkey[0]] != '1'}
              style={{ width, display: 'inline-block' }}
              viewAttr={viewAttr}
              onChange={value => this.onEdit(record, index, domkey[0], value == '0' ? '1' : '0')}
            />
            }
            { _type === 'BROWSER' &&
            <WeaBrowser
              ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@j9de1s@${domkey[0]}`}
			  {...browserConditionParam}
              layout={document.body}
              replaceDatas={this.getBrowerDatas(record, domkey[0])}
              
              style={{ width, display: 'inline-block' }}
            />
            }
          </span>,
        );
      }
    });
    return (
      <div>
        {_com}
      </div>
    );
  }
  getBrowerDatas(record, key) {
    const replaceDatas = [];
    if (record[`${key}span`] !== undefined) {
      const keys = record[key].split(',');
      const values = record[`${key}span`].split(',');
      if (keys.length === values.length) {
        keys.map((k, i) => {
          replaceDatas.push({ id: k, name: values[i] });
        });
      } else {
        // console.log('浏览按钮数据有误！！，显示名中不能包含有英文逗号" , "');
      }
    }
    return replaceDatas;
  }

  onEdit(record, index, key, value) {
    // record[key] = value
    const { datas } = this.state;
    const _datas = [...datas];
    if (record.pid) {
      for (let i = 0; i < _datas.length; i++) {
        if (_datas[i].dataId == record.pid) {
          _datas[i].child.detail[index][key] = value;
        }
      }
    } else {
      _datas[index][key] = value;
    }
    this.setState({ datas: _datas });
    // this.onChange(record, index, key, value);
  }


	getExpendRowRender=(record) => {
	  const { childColumns } = this.state;
	  return (
  <Table
  ecId={`${this && this.props && this.props.ecId || ''}_Table@y2t7hi`}
	      columns={this.getColumns(childColumns)}
  dataSource={record.child && record.child.detail}
  pagination={false}
  footer={this.setFooter(record.child)}
  showHeader={false}
	    />
	  );
	}
	setFooter(data) {
	  const { type } = this.props;
	  if (data) {
	    return (<table><tbody ><tr>
  <td width="55%" style={{ padding: '0 8px' }} />
  <td width="10%" style={{ padding: '0 8px', color: 'red' }}>{getLabel(523, '总计')}: </td>
  <td width="10%" style={{ padding: '0 8px', color: 'red' }}>{data.total}</td>
  <td width="10%" style={{ padding: '0 8px', color: 'red' }}>{type == 'pay' ? <span>{getLabel(1811, '余额')}： {data.balance}</span> : ''}</td>
  <td width="15%" style={{ padding: '0 8px' }} />
	    </tr></tbody></table>);
	  }
	  return <div />;
	}

	onChange(record, index, key, value) {
	  typeof this.props.onChange === 'function' && this.props.onChange(record, index, key, value);
	}
	saveRowList=(record, index) => {
	  typeof this.props.payRowSave === 'function' && this.props.payRowSave(record, index);
	}
	saveDetailList=(record, index, type) => {
	  typeof this.props.payDetailHandle === 'function' && this.props.payDetailHandle(record, index, type);
	}
	expendRowsChange=(arr) => {
	  // const {rowKeys} = this.state;
	  // const _rowKeys =  [].concat(rowKeys);
	  this.setState({
	    rowKeys: arr,
	  });
	}
}

export default ContractPayTable;
